package com.et.machine.manager.vm.setting

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.et.drive.info.LightStatusEnum
import com.et.drive.info.TemperatureStateEnum
import com.et.drive.info.Time
import com.et.machine.R
import com.et.machine.convert.lightTemperatureInfo
import com.et.machine.convert.machineInfo
import com.et.machine.databinding.FragmentSettingBinding
import com.et.machine.databinding.ItemAllBoxBinding
import com.et.machine.util.Adapter

class SettingFragment : Fragment() {


    private lateinit var viewModel: SettingViewModel
    private lateinit var binding: FragmentSettingBinding
    private lateinit var setTimeDialog: SetTimeDialog
    private lateinit var setTemperatureDialog: SetTemperatureDialog
    private lateinit var adapterBox: Adapter<SettingViewModel.Companion.Box, ItemAllBoxBinding>
    private var boxData = mutableListOf<SettingViewModel.Companion.Box>()
    private var selectedBox: SettingViewModel.Companion.Box =
        SettingViewModel.Companion.Box(false, 0)

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = FragmentSettingBinding.inflate(inflater, container, false).apply {
        binding = this
    }.root


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(SettingViewModel::class.java)
//        rg = RadioGroup(context)
//        if (machineInfo != null) {
//            addView()
//            if (lightTemperatureInfo.containsKey(selectedBox.box)) {
//                setRadioGroupCheck(selectedBox.box)
//            } else {
//                setRadioGroupCheck(0)
//            }
//        }

//        rg.setOnCheckedChangeListener { _, checkedId ->
//            if (lightTemperatureInfo.containsKey(checkedId)) {
//                notifyGoodsInfo(checkedId)
//            } else {
//                notifyGoodsInfo(0)
//            }
//        }
        initBar()
        initBoxAdapter()
        initSettingEvent()


    }

    private fun initSettingEvent() {
        /**
         * 设置制冷温度
         */
        binding.SettingCool.setOnClickListener {
            setTemperatureDialog = SetTemperatureDialog(
                requireContext(),
                lightTemperatureInfo[selectedBox.box]?.settingCoolTemperature.toString(),
            ) {
                viewModel.settingCoolTemperature(selectedBox.box, it.toInt())
                notifyGoodsInfo(selectedBox.box)
            }
            setTemperatureDialog.show()
        }

        /**
         * 设置制热温度
         */
        binding.SettingHot.setOnClickListener {
            setTemperatureDialog =
                SetTemperatureDialog(
                    requireContext(),
                    lightTemperatureInfo[selectedBox.box]?.settingHotTemperature.toString(),
                ) {
                    viewModel.settingHotTemperature(selectedBox.box, it.toInt())
                    notifyGoodsInfo(selectedBox.box)
                }
            setTemperatureDialog.show()
        }

        /**
         * 设置节能时间
         */
        binding.energySaveTime.setOnClickListener {
            setTimeDialog =
                SetTimeDialog(
                    requireContext(),
                    lightTemperatureInfo[selectedBox.box]?.energySavingTime
                ) {
                    viewModel.setEnergySaveTime(selectedBox.box, it)
                    notifyGoodsInfo(selectedBox.box)
                }
            setTimeDialog.show()
        }

        /**
         * 设置照明时间
         */
        binding.openLightTime.setOnClickListener {
            setTimeDialog =
                SetTimeDialog(
                    requireContext(),
                    lightTemperatureInfo[selectedBox.box]?.openLightTime
                ) {
                    viewModel.setOpenLightTime(selectedBox.box, it)
                    notifyGoodsInfo(selectedBox.box)
                }
            setTimeDialog.show()
        }

        /**
         * 设置照明状态
         */
        binding.light.setOnCheckedChangeListener { _, checkedId ->
            val lightStatus = when (checkedId) {
                R.id.light_auto -> LightStatusEnum.Auto
                R.id.light_open -> LightStatusEnum.AlwaysOpen
                R.id.light_close -> LightStatusEnum.AlwaysClose
                else -> LightStatusEnum.Auto
            }
            viewModel.setLightStatus(selectedBox.box, lightStatus)
        }

        /**
         * 设置左室状态
         */
        binding.left.setOnCheckedChangeListener { _, checkedId ->
            val leftTemp = when (checkedId) {
                R.id.left_disable -> TemperatureStateEnum.Disable
                R.id.left_hot -> TemperatureStateEnum.Hot
                R.id.left_cool -> TemperatureStateEnum.Cool
                else -> TemperatureStateEnum.Disable
            }
            viewModel.setLeftStatus(selectedBox.box, leftTemp)
        }

        /**
         * 设置右室状态
         */
        binding.right.setOnCheckedChangeListener { _, checkedId ->
            val rightTemp = when (checkedId) {
                R.id.right_disable -> TemperatureStateEnum.Disable
                R.id.right_hot -> TemperatureStateEnum.Hot
                R.id.right_cool -> TemperatureStateEnum.Cool
                else -> TemperatureStateEnum.Disable
            }
            viewModel.setRightStatus(selectedBox.box, rightTemp)
        }

        /**
         * 设置节能状态
         */
        binding.energy.setOnCheckedChangeListener { _, checkedId ->
            val energy = when (checkedId) {
                R.id.energy_open -> true
                R.id.energy_close -> false
                else -> false
            }
            if (!energy) {
                viewModel.setEnergySaveTime(selectedBox.box, Time(0, 0, 0, 0))
                notifyGoodsInfo(selectedBox.box)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initBar() {
        // back
        binding.layoutTitle.back.setOnClickListener {
            Navigation.findNavController(it).popBackStack()
        }

        binding.layoutTitle.uuid.text =
            "机器编号：${machineInfo?.uuid}"

        binding.layoutTitle.title.setText(R.string.setting_fragment_label)
    }

    private fun initBoxAdapter() {
        boxData = viewModel.addBoxList()
        boxData[0].apply {
            select = true
            selectedBox = this
        }
        // layout box
        binding.boxListview.also {
            it.adapter = Adapter(
                { view, _, data ->
                    view.box.text = viewModel.box2Name(data.box)
                    if (data.select) {
                        view.box.setBackgroundResource(R.drawable.radio_button_checked_icon)
                        notifyGoodsInfo(data.box)
                    } else {
                        view.box.setBackgroundResource(R.drawable.radio_button_dischecked_icon)
                    }

                    view.box.setOnClickListener {
                        selectedBox.select = false
                        data.select = true
                        selectedBox = data
                        adapterBox.notifyDataSetChanged()
                        notifyGoodsInfo(data.box)
                    }

                }, { inflater, viewGroup ->
                    ItemAllBoxBinding.inflate(inflater, viewGroup, false)
                }, boxData
            ).apply {
                adapterBox = this
            }
            it.layoutManager = LinearLayoutManager(requireContext()).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
        }
    }


    @SuppressLint("SetTextI18n")
    private fun notifyGoodsInfo(checkId: Int) {
        if (!lightTemperatureInfo.containsKey(checkId)) {
            binding.div.alpha = 0.3f
            Toast.makeText(context, "状态未知，请稍后...", Toast.LENGTH_LONG).show()
            return
        } else {
            binding.div.alpha = 1f
        }
        binding.light.check(
            when (lightTemperatureInfo[checkId]?.lightStatus) {
                LightStatusEnum.Auto -> R.id.light_auto
                LightStatusEnum.AlwaysClose -> R.id.light_close
                LightStatusEnum.AlwaysOpen -> R.id.light_open
                else -> R.id.light_auto
            }
        )
        binding.left.check(
            when (lightTemperatureInfo[checkId]?.leftRoomStatus) {
                TemperatureStateEnum.Cool -> R.id.left_cool
                TemperatureStateEnum.Hot -> R.id.left_hot
                TemperatureStateEnum.Disable -> R.id.left_disable
                else -> R.id.left_disable
            }
        )
        binding.right.check(
            when (lightTemperatureInfo[checkId]?.rightRoomStatus) {
                TemperatureStateEnum.Cool -> R.id.right_cool
                TemperatureStateEnum.Hot -> R.id.right_hot
                TemperatureStateEnum.Disable -> R.id.right_disable
                else -> R.id.right_disable
            }
        )

        if (lightTemperatureInfo[checkId]?.energySavingTime!!.startHour
            + lightTemperatureInfo[checkId]?.energySavingTime!!.startMin
            + lightTemperatureInfo[checkId]?.energySavingTime!!.endHour
            + lightTemperatureInfo[checkId]?.energySavingTime!!.endMin == 0
        ) {
            binding.energy.check(R.id.energy_close)
        } else {
            binding.energy.check(R.id.energy_open)
        }

        binding.energyStart.text =
            "${lightTemperatureInfo[checkId]?.energySavingTime!!.startHour}:${lightTemperatureInfo[checkId]?.energySavingTime!!.startMin}"
        binding.energyEnd.text =
            "${lightTemperatureInfo[checkId]?.energySavingTime!!.endHour}:${lightTemperatureInfo[checkId]?.energySavingTime!!.endMin}"
        binding.lightStart.text =
            "${lightTemperatureInfo[checkId]?.openLightTime!!.startHour}:${lightTemperatureInfo[checkId]?.openLightTime!!.startMin}"
        binding.lightEnd.text =
            "${lightTemperatureInfo[checkId]?.openLightTime!!.endHour}:${lightTemperatureInfo[checkId]?.openLightTime!!.endMin}"

        binding.settingCoolText.text =
            lightTemperatureInfo[checkId]?.settingCoolTemperature.toString() + "℃"
        binding.settingHotText.text =
            lightTemperatureInfo[checkId]?.settingHotTemperature.toString() + "℃"
        binding.ActualCool.text =
            lightTemperatureInfo[checkId]?.actualCoolTemperature.toString() + "℃"
        binding.ActualHot.text =
            lightTemperatureInfo[checkId]?.actualHotTemperature.toString() + "℃"
    }

}